package com.zzc.study.controller;

import com.zzc.study.service.ChatAssistant;
import dev.langchain4j.model.chat.StreamingChatLanguageModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.chat.response.StreamingChatResponseHandler;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RestController
@Slf4j
public class ChatLanguageModelController {
    @Autowired
    private ChatAssistant chatAssistant;
    @Autowired
    private StreamingChatLanguageModel streamingChatLanguageModel;


    // http://localhost:9005/chatstream/chat?prompt=湖北有什么好吃的
    @GetMapping(value = "/chatstream/chat")
    public Flux<String>chat(@RequestParam("prompt") String prompt, HttpServletResponse response){
        // 设置响应的字符编码
        response.setCharacterEncoding("UTF-8");
        return Flux.create(stringFluxSink -> {
            streamingChatLanguageModel.chat(prompt, new StreamingChatResponseHandler() {
                @Override
                public void onPartialResponse(String s) {
                    stringFluxSink.next(s);
                }

                @Override
                public void onCompleteResponse(ChatResponse chatResponse) {
                    stringFluxSink.complete();
                }

                @Override
                public void onError(Throwable throwable) {
                    stringFluxSink.error(throwable);
                }
            });
        });
    }
    @GetMapping(value = "/chatstream/chat2")
    public void chat2(@RequestParam(value = "prompt",defaultValue = "北京有什么好吃")String prompt) {
        System.out.println("---come in chat2");
        streamingChatLanguageModel.chat(prompt, new StreamingChatResponseHandler()
        {
            @Override
            public void onPartialResponse(String partialResponse)
            {
                System.out.println(partialResponse);
            }

            @Override
            public void onCompleteResponse(ChatResponse completeResponse)
            {
                System.out.println("---response over: "+completeResponse);
            }

            @Override
            public void onError(Throwable throwable)
            {
                throwable.printStackTrace();
            }
        });
    }
    @GetMapping(value = "/chatstream/chat3")
    public Flux<String> chat3(@RequestParam(value = "prompt", defaultValue = "南京有什么好吃")
                                  String prompt,HttpServletResponse response) {
        System.out.println("---come in chat3");
        // 设置响应的字符编码
        response.setCharacterEncoding("UTF-8");

        return chatAssistant.chat2(prompt);

    }
}
